package com.ychs.filter;

import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * copyright(c)2021 YYB.ALL rights Reserved
 * <p>
 * 描述:
 *
 * @author 原玉波
 * @version 1.0
 * @date 2021/7/13
 */
/*@WebFilter(filterName = "Filter1Coding",urlPatterns = "/*",
        initParams = {@WebInitParam(name = "coder",value = "utf-8")})*/
public class Filter1Coding implements Filter {
    private Logger logger = Logger.getLogger(this.getClass());
    private String coder = "utf-8";
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
       logger.info("进入编码过滤器");
       resp.setContentType("text/html;charset="+this.coder);
       //chain是过滤器链，doFilter是执行，也就是放行，允许通过。
        chain.doFilter(req,resp);
    }

    public void init(FilterConfig config) throws ServletException {
        String coder = config.getInitParameter("coder");
        //如果获取到了参数，按照参数来编码，否则按照默认的编码方式来编码。
        if(coder!=null){
            this.coder=coder;
        }
    }

}
